﻿using System.Collections.Generic;
using System.Text;
using RuTracker.Interface;
using RuTracker.Interface.Editors;
using RuTrackerLib.Editors.Links.Editors;
using RuTrackerLib.ServiceAttibutes;

namespace RuTrackerLib.Editors.Links
{
    [PerApplicationService]
    public class LinksEditor : IHtmlEditor
    {
        private readonly LinksLexer _lexer;
        private readonly ISessionStorage _sessionStorage;
        private readonly ITrackerAccessor _trackerAccessor;

        public LinksEditor(LinksLexer lexer
            , ISessionStorage sessionStorage
            , ITrackerAccessor trackerAccessor)
        {
            _trackerAccessor = trackerAccessor;
            _sessionStorage = sessionStorage;
            _lexer = lexer;
        }

        public string Edit(string html)
        {
            IList<Link> links = _lexer.Parse(html);
            StringBuilder result = new StringBuilder(html);

            foreach (Link link in links)
            {
                string directory = string.IsNullOrEmpty(_sessionStorage.CurrentFolder) ? _trackerAccessor.TrackerInfo.RootUrl : _sessionStorage.CurrentFolder;
                var editor = LinkEditorFactory.GetLinkEditor(link, _sessionStorage, directory);
                Link newLink = editor.EditLink(link);
                result.Replace(link.Html, newLink.Html);
            }

            return result.ToString();
        }
    }
}
